import express from 'express'
import logger from 'morgan'
import path from 'path'
import util from 'util'
import favicon from 'serve-favicon'
import cookie from 'cookie-parser'
import session from 'express-session'
import multer from 'multer'
export default () => {
  let app = express()
  // 处理跨域请求
  app.use((req,res,next) => {
    res.header('Access-Control-Allow-Origin', '*'); // 允许的请求源
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE') // 允许的请求方法
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token,Authorization') // 允许的请求头
    next()
  })
  // 加载静态资源
  app.use(express.static(path.join(__dirname,"../src")))
  // 输出日志
  app.use(logger('dev'))
  // 把图片变成icon图标
  app.use(favicon(path.join(__dirname,"../src/image/5.jpg")))
  // 使用seesion
  app.use(session({
    name: "session_id",
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    rolling: true,
    cookie: {
      maxAge: 1000*60*60*2 // 两小时过期
    }
  }))
  // 使用cookie模块
  app.use(cookie())
  
  let objMulter = multer({dest: path.join(path.dirname(__dirname),'public','file')})
  //上传任何文件
  app.use(objMulter.any())
  
  // 解析前端传入参数
  app.use(express.json())
  app.use(express.urlencoded({extended: false}))
  // 加载路由文件
  require(process.cwd() + "/routes/index.js")(app)
  // 当发生404页面错误的时候返回404.html文件
  app.use((req,res) =>{
    res.status(404)
    // res.sendFile(process.cwd() + "/src/404.html")
    res.redirect("/404.html")
  })
  // 封装异步
  app.listenAsync = util.promisify(app.listen)
  return app
}